package org.flywaydb.core.internal.database.dm;

import org.flywaydb.core.internal.database.base.Schema;
import org.flywaydb.core.internal.database.base.Table;
import org.flywaydb.core.internal.jdbc.JdbcTemplate;

import java.sql.SQLException;
import java.util.List;

/**
 * @author ZengShuo
 * @description: DMSchema
 * @since 2021/8/26 14:07
 */
public class DMSchema extends Schema<DMDatabase, DMTable> {
    /**
     * Creates a new schema.
     *
     * @param jdbcTemplate The Jdbc Template for communicating with the DB.
     * @param database     The database-specific support.
     * @param name         The name of the schema.
     */
    public DMSchema(JdbcTemplate jdbcTemplate, DMDatabase database, String name) {
        super(jdbcTemplate, database, name);
    }

    @Override
    protected boolean doExists() throws SQLException {
        List<String> strings = jdbcTemplate.queryForStringList("select distinct object_name TABLE_SCHEMA from all_objects where object_type = 'SCH' ");
        return strings.contains(name);
    }

    @Override
    protected boolean doEmpty() throws SQLException {
        return jdbcTemplate.queryForInt("select COUNT(1)  from all_tables WHERE owner= ?", name) == 0;
    }

    @Override
    protected void doCreate() throws SQLException {
        jdbcTemplate.execute("CREATE SCHEMA " + database.quote(name));
    }

    @Override
    protected void doDrop() throws SQLException {
        jdbcTemplate.execute("DROP SCHEMA " + database.quote(name));
    }

    @Override
    protected void doClean() throws SQLException {
    }

    @Override
    protected DMTable[] doAllTables() throws SQLException {
        List<String> tableNames = jdbcTemplate.queryForStringList("select TABLE_NAME  from all_tables WHERE owner = ?", name);
        DMTable[] tables = new DMTable[tableNames.size()];
        for (int i = 0; i < tableNames.size(); i++) {
            tables[i] = new DMTable(jdbcTemplate, database, this, tableNames.get(i));
        }
        return tables;
    }

    @Override
    public Table getTable(String tableName) {
        return new DMTable(jdbcTemplate, database, this, tableName);
    }

}
